import config from '../config';
import Local from '../utils/local';

export function CreateMapInstance({ container, style, updateState}) {
    if(!container || !window.atlas) return null;
    atlas.setConfig({
        accessToken: Local.get('access_token') || "eyJpZCI6ImRtZHoifQ.VWMeokSOCSl7c0ReuDePnwXD_bLK0d-PHgbOa8IMV_g",
        apiUrl: config.host.substring(0, config.host.length - 1)
    });
    const options = {
        container,
        minZoom: 4,
        maxZoom: 17
        // renderWorldCopies:false,
    };
    if(style) {
        options.style = style;
    }
    console.log(options)
    const map = new atlas.Map(options);

    return map;
}

export function createFullscreenControl() {
    if(!window.atlas) return null;

    class FullscreenControl extends atlas.FullscreenControl {
        setEvent({request, exit}) {
            this._requestCallback = request;
            this._exitCallback = exit;
        }

        _onClickFullscreen() {
            if (this._isFullscreen()) {
                if (this._exitCallback) this._exitCallback();
            } else if (this._container.requestFullscreen) {
                if (this._requestCallback) this._requestCallback();
            } else if ((this._container).mozRequestFullScreen) {
                if (this._requestCallback) this._requestCallback();
            } else if ((this._container).msRequestFullscreen) {
                if (this._requestCallback) this._requestCallback();
            } else if ((this._container).webkitRequestFullscreen) {
                if (this._requestCallback) this._requestCallback();
            }
            atlas.FullscreenControl.prototype._onClickFullscreen.call(this);
        }
    }

    return FullscreenControl;

}

/**
 * 定位到线面
 * @param {string} geo = [value] 线面的geojson
  * */
export function mapViewTo(params,map) {
	const geojsonLine = {
		"type": "FeatureCollection",
		"features": [
		  {
			  "type": "Feature",
			  "properties": {
				  "id": params.gid,
				  "name": params.name
			  },
			  "geometry": params.geom
		  }
		]
	};
	map.addSource('geodataLine', { type: 'geojson', data: geojsonLine });
	map.addLayer({
		'id': 'linelayer',
		'type': 'line',
		'source': "geodataLine",
		"layout": {
			"line-join": "round",
			"line-cap": "round"
		},
		"paint": {
			"line-color": "#BF93E4",
			"line-width": 5
		}
	});
	const coordinates = geojsonLine.features[0].geometry.coordinates;
	const bounds = coordinates.reduce(function (bounds, coord) {
		return bounds.extend(coord);
	}, new mapboxgl.LngLatBounds(coordinates[0], coordinates[0]));

	map.fitBounds(bounds, {
		padding: 20
	});
	
	map.on("click",(e) => {
		
	})
}